package org.javacraft.qa.model;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author jan
 */
public class TrafficJamState {

  private final Date date;

  private final int currentJamLength;

  public TrafficJamState( Date date, int jamLength ) {
    this.date = date;
    this.currentJamLength = jamLength;
  }

  public int getCurrentJamLength() {
    return currentJamLength;
  }

  public Date getDate() {
    return date;
  }

  @Override
  public boolean equals( Object obj ) {
    if ( obj == null ) {
      return false;
    }
    if ( getClass() != obj.getClass() ) {
      return false;
    }
    final TrafficJamState other = (TrafficJamState) obj;
    if ( this.date != other.date && ( this.date == null || !this.date.equals( other.date ) ) ) {
      return false;
    }
    if ( this.currentJamLength != other.currentJamLength ) {
      return false;
    }
    return true;
  }

  @Override
  public int hashCode() {
    int hash = 5;
    hash = 53 * hash + ( this.date != null ? this.date.hashCode() : 0 );
    hash = 53 * hash + this.currentJamLength;
    return hash;
  }

  /**
   * Converts one entry of a traffic jam report to a 
   * TrafficJamState.
   * 
   * @param state String entry formatted as day/month/year,hour:min,km,100m (ie 05/08/2010,22:0,19,4)
   * @return TrafficJamState equivalent
   */
  public static TrafficJamState fromReportEntry( final String state ) {
    final String[] dateFields = state.split( "," )[0].split( "/" );
    final String[] timeFields = state.split( "," )[1].split( ":" );
    final Calendar calendar = Calendar.getInstance();
    calendar.set( Calendar.YEAR, Integer.parseInt( dateFields[2]) );
    calendar.set( Calendar.MONTH, Integer.parseInt( dateFields[1]) - 1 );
    calendar.set( Calendar.DAY_OF_MONTH, Integer.parseInt( dateFields[0]) );
    calendar.set( Calendar.HOUR_OF_DAY, Integer.parseInt( timeFields[0]) );
    calendar.set( Calendar.MINUTE, Integer.parseInt( timeFields[1]) );
    calendar.set( Calendar.SECOND, 0 );
    calendar.set( Calendar.MILLISECOND, 0 );
    int length = Integer.parseInt( state.split( ",")[2] ) * 1000;
    length += Integer.parseInt( state.split( ",")[3] ) * 100;
    
    return new TrafficJamState( calendar.getTime(), length );
  }
}
